package com.yanqu.road.server.manager.activity.suitang.manager;

import com.yanqu.road.entity.activity.suitang.config.SuiTangConfigSync;
import com.yanqu.road.entity.activity.suitang.data.CrossSuiTangData;
import com.yanqu.road.entity.activity.suitang.data.CrossSuiTangUnionJoinData;
import com.yanqu.road.entity.activity.suitang.data.CrossSuiTangUserData;
import com.yanqu.road.entity.activity.suitang.entity.union.CrossSuiTangUnionJoinMember;
import com.yanqu.road.entity.player.CrossUserBaseInfo;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroup;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroupUnion;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroupUser;
import com.yanqu.road.logic.helper.ActivityHelper;
import com.yanqu.road.pb.activity.suitang.SuiTang;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.activity.suitang.activity.CrossSuiTangBaseActivity;
import com.yanqu.road.server.manager.union.activitygroup.Cross2UnionActivityGroupMgr;
import com.yanqu.road.server.manager.user.CrossUserMgr;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.date.DateHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

public class CrossSuiTangLockMemberMgr extends CrossBaseActivityMgr {

    // 管理数据 =》 Map<String, CrossSuiTangUnionJoinData>
    protected static Logger logger = LogManager.getLogger(CrossSuiTangLockMemberMgr.class.getName());

    private AtomicLong waitTime = new AtomicLong(0);

    @Override
    public void init() {
        super.init();
    }

    /*
     * 锁商会
     */
    public boolean lockUnion() {
        if (activity == null) {
            return false;
        }
        SuiTangConfigSync config = activity.getConfig();
        if (config == null) {
            return false;
        }
        CrossSuiTangData crossSuiTangData = activity.getCrossSuiTangData();
        if (crossSuiTangData == null) {
            return false;
        }
        int groupId = activity.getGroupId();
        int activityId = config.getActivityId();
        UnionActivityGroup groupData = Cross2UnionActivityGroupMgr.getGroupData(activityId, groupId);
        if (groupData == null) {
            return false;
        }
        if (!ActivityHelper.activityInShowTime(config.getActivityInfo())) {
            return false;
        }

        if (!isLockTime()) {
            // 把锁标志重置下
            //crossSuiTangData.setLockUnion(false);
            // 未到锁名单时间
            updateUnionLock();
            // 更新参与者的数据
            checkUnionJoinMember(null);
        } else {
            if (crossSuiTangData.getLockUnion()) {
                return false;
            }
            if (lock()) {
                crossSuiTangData.setLockUnion(true);
                // 如果开启npc模式，就往锁名单中加点料
//                if (activity.getNpcTestActivityMgr().isNpcMode()){
//                    activity.getNpcTestActivityMgr().CreateNpcUnion();
//                }
                logger.debug("【隋唐】锁名单完成");
                // 锁定完成，进行活动分组
                activity.getGroupActivityMgr().groupUnion();
                return true;
            }
        }
        return false;
    }

    /*
     * 锁定
     */
    private boolean lock() {
        // 防止某个区服紧急维护，导致拉取不到玩家数据，超过5分钟仍然拉取不到，则给予这些玩家一个默认值。
        waitTime = waitTime.longValue() == 0 ? new AtomicLong(System.currentTimeMillis() + 5 * DateHelper.MINUTE_MILLIONS) : waitTime;
        updateUnionLock();
        // 检查商会成员数据
        if (!checkUnionJoinMember(null)) {
            return false;
        }
        return true;
    }

    /*
     * 更新锁商会名单
     */
    private void updateUnionLock() {
        if (activity == null) {
            return;
        }
        Map<String, CrossSuiTangUnionJoinData> unionJoinDataMap = activity.getUnionJoinDataMap();
        if (unionJoinDataMap == null) {
            return;
        }
        SuiTangConfigSync config = activity.getConfig();
        if (config == null) {
            return;
        }
        CrossSuiTangData crossSuiTangData = activity.getCrossSuiTangData();
        if (crossSuiTangData == null) {
            return;
        }
        int groupId = activity.getGroupId();
        int activityId = config.getActivityId();
        UnionActivityGroup groupData = Cross2UnionActivityGroupMgr.getGroupData(activityId, groupId);
        if (groupData == null) {
            return;
        }
        if (!ActivityHelper.activityInShowTime(config.getActivityInfo())) {
            return;
        }

        ConcurrentHashMap<String, UnionActivityGroupUnion> unionDataMap = groupData.getUnionDataMap();
        if (unionDataMap == null || unionDataMap.isEmpty()) {
            return;
        }
        for (UnionActivityGroupUnion union : unionDataMap.values()) {
            updateUnion(union);
        }
    }

    public void updateUnion(UnionActivityGroupUnion union) {
        SuiTangConfigSync config = activity.getConfig();
        int activityId = config.getActivityId();
        int groupId = activity.getGroupId();
        Map<String, CrossSuiTangUnionJoinData> unionJoinDataMap = activity.getUnionJoinDataMap();
        if (unionJoinDataMap == null) {
            return;
        }
        if (!ActivityHelper.activityInShowTime(config.getActivityInfo())) {
            return;
        }
        // 处理商会名单
        CrossSuiTangUnionJoinData unionJoinData = unionJoinDataMap.get(union.getUnionUid());
        if (unionJoinData == null
                && !activity.getCrossSuiTangData().getLockUnion()
                && unionJoinDataMap.size() < config.getParamConfig().getSuiTangJoinCond()
                && union.getRank() <= config.getParamConfig().getSuiTangJoinCond()
        ) {
            unionJoinData = new CrossSuiTangUnionJoinData();
            unionJoinData.setActivityId(activityId);
            unionJoinData.setGroupId(groupId);
            unionJoinData.setUnionUid(union.getUnionUid());
            unionJoinData.setUnionBaseInfo(union.getUnionBaseInfo());
            unionJoinData.setMemberMap(new ConcurrentHashMap<>());
            unionJoinData.setInsertOption();
            unionJoinDataMap.put(unionJoinData.getUnionUid(), unionJoinData);
        }
        if (unionJoinData == null) {
            return;
        }

        // 处理成员名单
        Map<Long, CrossSuiTangUnionJoinMember> memberMap = unionJoinData.getMemberMap();
        Map<Long, CrossSuiTangUnionJoinMember> tempMemberMap = new ConcurrentHashMap<>();
        for (UnionActivityGroupUser member : union.getUserMap().values()) {
            CrossSuiTangUserData userData = activity.getUserData(member.getUserId());
            if (userData == null) {
                continue;
            }
            CrossSuiTangUnionJoinMember newMember = memberMap.get(member.getUserId());
            if (newMember == null) {
                newMember = new CrossSuiTangUnionJoinMember(member.getUserId(), member.getServerId());
            }
            newMember.setPosition(member.getPosition());
            tempMemberMap.put(newMember.getUserId(), newMember);
            // 锁名单时，把玩家加入内存
            userData.setUnionUid(union.getUnionUid());
        }
        unionJoinData.setMemberMap(tempMemberMap);
//        if (!activity.getCrossSuiTangData().getLockUnion()) {
//            Map<Long, CrossSuiTangUnionJoinMember> tempMemberMap = new ConcurrentHashMap<>();
//            for (UnionActivityGroupUser member : union.getUserMap().values()) {
//                CrossSuiTangUnionJoinMember newMember = memberMap.remove(member.getUserId());
//                if (newMember == null) {
//                    newMember = new CrossSuiTangUnionJoinMember(member.getUserId(), member.getServerId());
//                }
//                newMember.setPosition(member.getPosition());
//                tempMemberMap.put(newMember.getUserId(), newMember);
//                // 锁名单时，把玩家加入内存
//                activity.getUserData(member.getUserId()).setUnionUid(union.getUnionUid());
//            }
//            unionJoinData.setMemberMap(tempMemberMap);
//        } else {
//            for (UnionActivityGroupUser member : union.getUserMap().values()) {
//                CrossSuiTangUnionJoinMember newMember = memberMap.get(member.getUserId());
//                if (newMember != null) {
//                    newMember.setPosition(member.getPosition());
//                }
//            }
//        }
        unionJoinData.setUpdateOption();
    }

    /*
     * 检查报名商会成员数据
     */
    public boolean checkUnionJoinMember(String optionalUnionUid) {
        // 检查报名的商会中，区服未上传数据的成员
        Map<Long, List<Long>> serverUserMap = new ConcurrentHashMap<>();
        for (CrossSuiTangUnionJoinData unionJoin : activity.getUnionJoinDataMap().values()) {
            if (optionalUnionUid != null && !Objects.equals(unionJoin.getUnionUid(), optionalUnionUid)) {
                continue;
            }
            for (CrossSuiTangUnionJoinMember joinMember : unionJoin.getMemberMap().values()) {
                if (waitTime.longValue() < System.currentTimeMillis() && !activity.getCrossSuiTangData().getLockUnion()) {
                    UserBaseInfo userBaseInfo = CrossUserMgr.getUserBaseInfo(joinMember.getUserId());
                    // 超过的等待时间，给予玩家一个初始值 100
                    joinMember.setEarnSpeed(Math.max(userBaseInfo == null ? 100 : userBaseInfo.getEarnSpeed().longValue(), 100));
                    joinMember.setTopAbility(Math.max(userBaseInfo == null ? 100 : userBaseInfo.getTotalAbility().longValue(), 100));
                }
                if (joinMember.getEarnSpeed() == 0 || joinMember.getTopAbility() == 0) {
                    serverUserMap.putIfAbsent(joinMember.getServerId(), new ArrayList<>());
                    serverUserMap.get(joinMember.getServerId()).add(joinMember.getUserId());
                }
            }
        }
        boolean suc = true;
        for (Map.Entry<Long, List<Long>> entry : serverUserMap.entrySet()) {
            long serverId = entry.getKey();
            List<Long> userId = entry.getValue();
            if (userId.size() > 0) {
                sendGetUnionMemberMsg(serverId, userId);
                suc = false;
            }
        }
        return suc;
    }

    /**
     * 请求游戏服上传玩家信息
     */
    private void sendGetUnionMemberMsg(long serverId, List<Long> userId) {
        SuiTang.SuiTangBingGetMemberReqMsg.Builder builder = SuiTang.SuiTangBingGetMemberReqMsg.newBuilder();
        builder.setActivityId(activity.getConfig().getActivityId());
        builder.addAllUserId(userId);
        builder.setGroupId(activity.getGroupId());
        MessageHelper.sendPacket(serverId, 0, YanQuMessageUtils.buildMessage(GameProtocol.S_CROSS_SUI_TANG_GET_UNION_MEMBER_REQ, builder));
    }
}
